﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;
using QLZJFurnitureSCM.Model;
using System.Data.SqlClient;
using System.Data;

namespace QLZJFurnitureSCM.DAL
{
    public class PurchaseDAO:IBaseDAO<Purchase>, IPurchaseDAO
    {
        private string connectionString = DALFactory.CONNECTIONSTRING;
        private SqlConnection sqlConn = null;
        private SqlDataAdapter adapter = null;

        public PurchaseDAO()
        {
            sqlConn = new SqlConnection(connectionString);
        }

        public Purchase Create(Purchase t)
        {
            DataContext dataContext = new DataContext(connectionString);
            try
            {
                string query = string.Format("insert into Purchase (purchaseDate,purchaseProductType,purchaseProductName,purchaseCount,purchasePrice,purchaseByUser) values('{0}','{1}','{2}',{3},{4},'{5}'); select @@identity;", 
                    t.PurchaseDate, t.PurchaseProductType, t.PurchaseProductName, t.PurchaseCount, t.PurchasePrice, t.PurchaseByUser);
                Console.WriteLine("Purchase Create: " + query);
                if(sqlConn.State != ConnectionState.Open)
                    sqlConn.Open();
                SqlCommand sqlCmd = new SqlCommand(query, sqlConn);
                object o = sqlCmd.ExecuteScalar();
                sqlConn.Close();
                if(o!=null)
                    t.PurchaseId = int.Parse(o.ToString());
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex);
                return Create(t);
            }
            return t;
            
        }

        public Purchase Read(Purchase t)
        {
            throw new NotImplementedException();
        }

        public DataTable ReadInDataTable(bool descSort)
        {
            string query = "select * from Purchase";
            if(descSort)
                query = query + " order by purchaseId desc;";
            DataTable dt = null;
            sqlConn.Open();
            dt = new DataTable();
            adapter = new SqlDataAdapter(query, sqlConn);
            adapter.Fill(dt);
            adapter.Dispose();
            sqlConn.Close();
            return dt;
        }

        public bool Update(Purchase t)
        {
            throw new NotImplementedException();
        }

        public bool Delete(Purchase t)
        {
            throw new NotImplementedException();
        }

        public List<Purchase> ReadAll()
        {
            DataContext dataContext = new DataContext(connectionString);
            IEnumerable<Purchase> enumPurchase = dataContext.ExecuteQuery<Purchase>("select * from Purchase;");
            return enumPurchase.ToList();
        }
    }
}
